<template>
   <a-spin :spinning="confirmLoading">
     <j-form-container :disabled="formDisabled">
       <!-- 主表单区域 -->
       <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
         <a-row>
          <a-col :xs="24" :sm="12">
            <a-form-model-item label="入库单编码" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="code">
              <a-input v-model="model.code" placeholder="请输入入库单编码" disabled></a-input>
            </a-form-model-item>
          </a-col>
          <!-- <a-col :xs="24" :sm="12">
            <a-form-model-item label="关联采购订单" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="orderCode">
              <j-popup
                v-model="model.orderCode"
                field="orderCode"
                org-fields="code"
                dest-fields="orderCode"
                code="order_select"
                :multi="false"
                @input="popupCallback"
                />
            </a-form-model-item>
          </a-col> -->
          <a-col :xs="24" :sm="12">
            <a-form-model-item label="入库仓库" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="repositoryName">
              <j-popup
                v-model="model.repositoryName"
                field="repositoryName"
                org-fields="name,code"
                dest-fields="repositoryName,repositoryCode"
                code="select_repository"
                :multi="false"
                @input="popupCallback"
                />
            </a-form-model-item>
          </a-col>
          <a-col :xs="24" :sm="12">
            <a-form-model-item label="入库人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="inPeople">
              <j-select-user-by-dep v-model="model.inPeople" :multi="true" />
            </a-form-model-item>
          </a-col>
          <a-col :xs="24" :sm="12">
            <a-form-model-item label="到货日期" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="deliveryTime">
              <j-date placeholder="请选择到货日期" v-model="model.deliveryTime" :show-time="true" date-format="YYYY-MM-DD HH:mm:ss" style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <a-col :xs="24" :sm="12">
            <a-form-model-item label="入库日期" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="inTime">
              <j-date placeholder="请选择入库日期" v-model="model.inTime" :show-time="true" date-format="YYYY-MM-DD HH:mm:ss" style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <a-col :xs="24" :sm="12">
            <a-form-model-item label="附件" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="attachment">
              <j-upload v-model="model.attachment"   :number=10 :before-upload="beforeUpload"></j-upload>
            </a-form-model-item>
          </a-col>
          <a-col :xs="24" :sm="12">
            <a-form-model-item label="总计金额" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="total">
              <a-input-number v-model="model.total" placeholder="请输入总计金额" style="width: 100%" disabled/>
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
     </j-form-container>
      <!-- 子表单区域 -->
      <a-tabs v-model="activeKey" @change="handleChangeTabs">
        <a-tab-pane tab="入库物品" :key="refKeys[0]" :forceRender="true">
          <j-editable-table
            :ref="refKeys[0]"
            :loading="purchaseStockInGoodsTable.loading"
            :columns="purchaseStockInGoodsTable.columns"
            :dataSource="purchaseStockInGoodsTable.dataSource"
            :maxHeight="300"
            :disabled="formDisabled"
            :rowNumber="true"
            :rowSelection="true"
            :actionButton="true"
            @valueChange="valueChange"
            />
        </a-tab-pane>
      </a-tabs>
    </a-spin>
</template>

<script>

  import { FormTypes,getRefPromise,VALIDATE_NO_PASSED } from '@/utils/JEditableTableUtil'
  import { JEditableTableModelMixin } from '@/mixins/JEditableTableModelMixin'
  import { validateDuplicateValue } from '@/utils/util'
  import {stockInCodeRule} from '@/api/api'
  import currency from 'currency.js'

  export default {
    name: 'PurchaseStockInForm',
    mixins: [JEditableTableModelMixin],
    components: {
    },
    data() {
      return {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
        model:{
          code:''
        },
        validatorRules: {
          repositioryName: [
            { required: true, message: '请选择仓库'},
          ],
           inPeople: [
            { required: true, message: '请选择入库人'},
          ],
           inTime: [
            { required: true, message: '请选择入库日期'},
          ],
        },
        // 新增时子表默认添加几行空数据
        addDefaultRowNum: 1,
        refKeys: ['purchaseStockInGoods', ],
        tableKeys:['purchaseStockInGoods', ],
        activeKey: 'purchaseStockInGoods',
        // 入库物品
        purchaseStockInGoodsTable: {
          loading: false,
          dataSource: [],
          columns: [
            {
              title: '物品名称',
              key: 'goodsName',
              type: FormTypes.popup,
              popupCode:"purchase_goods",
              destFields:"goodsName,goodsTypeCode,goodsCode,size,unit,unitPrice,brand",
              orgFields:"goods_name,goods_type_code,code,size,unit,unit_price,brand",
              width:"200px",
              param:{},
              placeholder: '请输入${title}',
              defaultValue:'',
              validateRules: [{ required: true, message: '请输入${title}'},],
            },
            {
              title: '物品分类',
              key: 'goodsTypeCode',
              type: FormTypes.select,
              dictCode:"purchase_goods_type",
              disabled:true,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '物品编码',
              key: 'goodsCode',
              type: FormTypes.input,
              disabled:true,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '品牌',
              key: 'brand',
              type: FormTypes.input,
              disabled:true,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '规格/尺寸/型号',
              key: 'size',
              type: FormTypes.input,
              disabled:true,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '单位',
              key: 'unit',
              type: FormTypes.select,
              dictCode:"purchase_unit",
              disabled:true,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '单价',
              key: 'unitPrice',
              type: FormTypes.inputNumber,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
              validateRules: [{
                handler(type, value, row, column, callback, target){
                  let {values} = target.getValuesSync({validate: false, rowIds: [row.id]})
                  const unitPri = Number(values[0].unitPrice)
                  if(!unitPri){
                    callback(false, `单价不能为空`)
                  }else{
                    callback(true)
                  }
                },
                message: '${title}默认提示'
              },
              {pattern: /^\d+(\.{0,1}\d+){0,1}$/, message: '${title}必须非负数'}]
            },
            {
              title: '采购数量',
              key: 'number',
              type: FormTypes.input,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
              validateRules: [{
                handler(type, value, row, column, callback, target){
                  let {values} = target.getValuesSync({validate: false, rowIds: [row.id]})
                  const num = Number(values[0].number)
                  if(!num){
                    callback(false, `采购数量不能为空`)
                  }else{
                    callback(true)
                  }
                },
                message: '${title}默认提示'
              }]
            },
            {
              title: '本次入库数量',
              key: 'finalNumber',
              type: FormTypes.inputNumber,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
              validateRules: [{
                handler(type, value, row, column, callback, target){
                  let {values} = target.getValuesSync({validate: false, rowIds: [row.id]})
                  const finalNum = Number(values[0].finalNumber)
                  if(!finalNum){
                    callback(false, `本次入库数量不能为空`)
                  }
                  const num = Number(values[0].number)
                  if(value > num){
                    callback(false, `本次入库数量不能大于采购数量`)
                  }else{
                    callback(true)
                  }
                },
                message: '${title}默认提示'
              }]
            },
            {
              title: '小计',
              key: 'total',
              type: FormTypes.inputNumber,
              disabled:true,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },

            {
              title: 'goods_name',
              key: 'goods_name',
              type:"hidden"
            },

            {
              title: 'goods_type_code',
              key: 'goods_type_code',
              type:"hidden"
            },

            {
              title: 'goods_code',
              key: 'goods_code',
              type:"hidden"
            },



            {
              title: 'unit_price',
              key: 'unit_price',
              type:"hidden"
            },
          ]
        },
        url: {
          add: "/purchase/purchaseStockIn/add",
          edit: "/purchase/purchaseStockIn/edit",
          purchaseStockInGoods: {
            list: '/purchase/purchaseStockIn/queryPurchaseStockInGoodsByMainId'
          },
        }
      }
    },
    props: {
      //表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      }
    },
    computed: {
      formDisabled(){
        return this.disabled
      },
    },
    created () {
    
    },
    methods: {
      valueChange(obj){
        // console.log(obj)
        if(obj.row.unitPrice >= 0 && obj.row.finalNumber >= 0){
          let sub_total = currency(obj.row.unitPrice).multiply(obj.row.finalNumber)
            if(sub_total != obj.row.total){
              obj.target.setValues([{
                rowKey: obj.row.id,
                values: {
                  'total': sub_total
                }
              }])
            }
        }
        obj.target.getValues((error,values) => {
          let total = 0
          values.map(item => {
            // total += item.total
            total =currency(total).add(item.total)
          })
          console.log(total)
          this.model.total = total.value
        })
    },
      //初始化入库编码
      init(){
        stockInCodeRule({}).then((res)=>{
          if(res.success){
            this.model.code = res.result;
          }else{
            this.$message.warning(res.message);
          }
        });
      },
     addBefore(){
            this.purchaseStockInGoodsTable.dataSource=[]
      },
      getAllTable() {
        let values = this.tableKeys.map(key => getRefPromise(this, key))
        return Promise.all(values)
      },
      /** 调用完edit()方法之后会自动调用此方法 */
      editAfter() {
        this.$nextTick(() => {
        })
        // 加载子表数据
        if (this.model.id) {
          let params = { id: this.model.id }
          this.requestSubTableData(this.url.purchaseStockInGoods.list, params, this.purchaseStockInGoodsTable)
        }
        if(!this.model.id){
          this.init();
        }
      },
      //校验所有一对一子表表单
    validateSubForm(allValues){
        return new Promise((resolve,reject)=>{
          Promise.all([
          ]).then(() => {
            resolve(allValues)
          }).catch(e => {
            if (e.error === VALIDATE_NO_PASSED) {
              // 如果有未通过表单验证的子表，就自动跳转到它所在的tab
              this.activeKey = e.index == null ? this.activeKey : this.refKeys[e.index]
            } else {
              console.error(e)
            }
          })
        })
    },
      /** 整理成formData */
      classifyIntoFormData(allValues) {
        let main = Object.assign(this.model, allValues.formValue)

        return {
          ...main, // 展开
          purchaseStockInGoodsList: allValues.tablesValue[0].values,
        }
      },
      validateError(msg){
        this.$message.error(msg)
      },
     close() {
        this.visible = false
        this.$emit('close')
        this.$refs.form.clearValidate();
      },
     popupCallback(value,row){
        this.model = Object.assign(this.model, row);
        this.purchaseStockInGoodsTable.columns[0].param = row;
     },
     beforeUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.$message.error('文件过大');
      }
      const isMax = this.model.attachment && this.model.attachment.split(',').length >= 10
      if(isMax){
        this.$message.error('最多上传文件数10个');
      }
      return isLt2M && !isMax;
    },    

    }
  }
</script>

<style scoped>
</style>